/* ----------------------------------------------------------------------------
* File: skype_instance.cpp
*
* Desc: COM instance of Skype object - definition
*
* Created: 03/05/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#include "skype_instance.h"
using namespace SkypeInstance;


InstanceManager::InstanceManager(DWORD WaitTime, EventHandler* Handler) throw(SkypeException::CommonException)
	: m_Skype(NULL)
{
	CoInitialize(NULL);

	// Create instance
	HRESULT hr = m_Skype.CreateInstance(__uuidof(SKYPE4COMLib::Skype));
	if (hr != S_OK)
		throw SkypeException::CommonException("Unable to create COM instance");

	// Connect to Skype API without waiting
	m_Skype->Attach(6, VARIANT_FALSE);

	// Wait API permission
	SKYPE4COMLib::TAttachmentStatus attachStatus = m_Skype->GetAttachmentStatus();
	while (attachStatus != SKYPE4COMLib::TAttachmentStatus::apiAttachSuccess)
	{
		if (attachStatus == SKYPE4COMLib::TAttachmentStatus::apiAttachRefused)
		{
			m_Skype->Release();
			CoUninitialize();
			throw SkypeException::CommonException("Object was refused");
		}
		else
		{
			// notify about attaching process
			Handler->OnAttaching();

			// attaching in process, so service is running
			//Env.serviceStatus.dwCurrentState = SERVICE_RUNNING;
			//Env.serviceStatus.dwCheckPoint++;
			//SetServiceStatus(Env.hStatus, &Env.serviceStatus);
		}

		Sleep(WaitTime);
		attachStatus = m_Skype->GetAttachmentStatus();
	}
}
/************************************************************************/
/*	Get Skype instance													*/
/************************************************************************/
SKYPE4COMLib::ISkypePtr InstanceManager::GetObject()
{
	return m_Skype;
}

InstanceManager::~InstanceManager()
{
	m_Skype = NULL;
	CoUninitialize();
}